/*
 * date.c
 *
 * Sisältää daten tietorakenteen, uuden daten luonnin,
 * daten parsiminen stringistä sekä date vertailun
 *
 */

#include<stdio.h>
#include <ctype.h>
#include <wchar.h>
#include "date.h"


const date NULL_DATE = {0, 0, -1};

/*
 *	Luo uuden Date:n
 */
date new_date(char day, char month, int year) { //Joni
    date tmp;
    tmp.day = day;
    tmp.month = month;
    tmp.year = year;
    return tmp;
}

/*
 *	Luo Daten stringistä (muoto dd-mm-yyyy)
 */
date date_from_string(wchar_t* str) { //Ossi
    int day = 0, month = 0, year = 0;
    int res = swscanf(str, L"%d-%d-%d", &day, &month, &year);
    if (!(res == 3) || month > 12 || month < 1 || day > 31 || day < 1) {
        return NULL_DATE;
    }
    return new_date((char) day, (char) month, year);
}

/*
 *	Vertailee kahta datea keskenään
 */
int date_compare(const void* date1, const void* date2) { //Ossi
    if (date1 == NULL) return -1;
    if (date2 == NULL) return 1;
    date* d1 = (date*) date1;
    date* d2 = (date*) date2;
    int ydiff = d1->year - d2->year;
    if (ydiff) return ydiff;

    int mdiff = d1->month - d2->month;
    if (mdiff) return mdiff;

    int ddiff = d1->day - d2->day;
    if (ddiff) return ddiff;

    return 0;
}
